package fr.generali.accueilclient.gwt.client.view;

import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.web.bindery.event.shared.HandlerRegistration;

import fr.generali.accueilclient.gwt.client.presenter.ViewPresenter;

/**
 * Implémentation par défaut de {@link PopupView}. Les vues qui héritent de
 * cette classe doivent impérativement avoir la méthode {@link #asWidget()} qui
 * retourne un {@link PopupPanel} ou une sous-classe de ce dernier (par exemple
 * {@link DecoratedPopupPanel}, {@link DialogBox}.
 */
public abstract class PopupViewImpl<P extends ViewPresenter< ? >> extends BaseView<P> implements PopupView<P> {

    private HandlerRegistration closeHandlerRegistration;

    protected PopupViewImpl() {
    }

    @Override
    public void center() {

        asPopupPanel().center();
    }

    @Override
    public void hide() {
        asPopupPanel().hide();
    }

    @Override
    public void setCloseHandler(final PopupViewCloseHandler popupViewCloseHandler) {
        if (closeHandlerRegistration != null) {
            closeHandlerRegistration.removeHandler();
        }
        if (popupViewCloseHandler == null) {
            closeHandlerRegistration = null;
        } else {
            closeHandlerRegistration = asPopupPanel().addCloseHandler(new CloseHandler<PopupPanel>() {
                @Override
                public void onClose(CloseEvent<PopupPanel> event) {
                    popupViewCloseHandler.onClose();
                }
            });
        }
    }

    @Override
    public void setPosition(int left, int top) {
        asPopupPanel().setPopupPosition(left, top);
    }

    @Override
    public void show() {
        asPopupPanel().show();
    }

    /**
     * Retrieves this view as a {@link PopupPanel}. See {@link #asWidget()}.
     * 
     * @return This view as a {@link PopupPanel} object.
     */
    public PopupPanel asPopupPanel() {
        // asWidget() est implémentée par la vue qui étend cette classe.
        // asWidget() soit retourner un sous-type de PopupPanel.
        return (PopupPanel ) asWidget();
    }

    @Override
    public void setModal(boolean modal) {
        asPopupPanel().setModal(modal);
    }

    @Override
    public boolean isShowing() {
        return asPopupPanel().isShowing();
    }
}
